package controller;

import entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;

// 配置Servlet映射路径，与前端请求路径对应
@WebServlet("/api/user/info")
public class UserInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // Jackson JSON处理工具
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应格式为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 获取当前会话
        HttpSession session = request.getSession(false);

        // 构建响应结果对象
        Result result = new Result();

        if (session != null && session.getAttribute("userId") != null) {
            // 假设登录时已将用户信息存入session，键为"user"
            result.setSuccess(true);
            result.setData(session.getAttribute("username")); // 只返回需要的用户名信息
        } else {
            // 未登录或会话失效
            result.setSuccess(false);
            result.setMessage("用户未登录或会话已过期");
        }

        // 将结果转换为JSON并写入响应
        objectMapper.writeValue(response.getWriter(), result);
    }

    // 响应结果封装类
    static class Result {
        private boolean success;
        private String message;
        private Object data;

        // getter和setter
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        public Object getData() { return data; }
        public void setData(Object data) { this.data = data; }
    }
}
